package com.ruiyou.uu.encryption;

import java.io.Console;
import java.io.File;

public class Yjm {
    private static void usage() {
        System.out.printf("Usage:" +
                "%n  java Yjm.java [-E] [-R] <dir>" +
                "%n  -E encrypt, default decrypt" +
                "%n  -R recursive, default not" +
                "%n  dir Directory%n");
        System.exit(0);
    }

    private static String getPassword() {
        Console con = System.console();
        char[] buf;
        while (true) {
            System.out.print("password>");
            buf = con.readPassword();
            String rs;
            do {
                rs = con.readLine(
                        "Entered '%s', sure?(Y/N, Y)>",
                        new String(buf)
                );
            } while (!rs.isEmpty() && !rs.equalsIgnoreCase("Y") &&
                    !rs.equalsIgnoreCase("N"));
            if (!rs.equalsIgnoreCase("N"))
                break;
        }
        return new String(buf);
    }

    public static void main(String[] args) {
        if (args.length < 1)
            usage();
        File dir = new File(args[args.length - 1]);
        if (!dir.exists() || !dir.isDirectory()) {
            System.err.println("Dir not found: " + dir.getPath());
            return;
        }
        boolean isEncrypt = false, isRecurs = false;
        for (int i = 0; i < args.length - 1; i++) {
            if (args[i].equalsIgnoreCase("-E")) {
                isEncrypt = true;
            } else if (args[i].equalsIgnoreCase("-R")) {
                isRecurs = true;
            } else {
                System.out.println("Unknown option: " + args[i]);
                usage();
            }
        }
        String pw = getPassword();
        EncryptionUtil util = new EncryptionUtil(
                System.out::println
        );
        util.start(dir, isRecurs, pw, isEncrypt);
        if (isEncrypt || util.getSucC() == 0)
            return;
        while (true) {
            System.out.print(
                    "Restore encryption status?(Y/N, N)>");
            String s = System.console().readLine();
            if (s.length() < 1 || s.equalsIgnoreCase("N")) {
                break;
            } else if (s.equalsIgnoreCase("Y")) {
                util.start(dir, isRecurs, pw, true);
                break;
            }
        }
    }
}
